package awesome.site.loader;

import java.io.File;
import java.util.logging.Logger;

import awesome.site.proprietor.SiteProprietor;
import awesome.site.proprietor.WebObjectProprietor;

/**
 * Loads new/updated files into the SiteProprietor.
 * 
 * @author Bee Vo
 * 
 */
public class FileSystemLoader {

	SiteProprietor siteProprietor;
	private File rootDirectory;
	
	/**
	 * 
	 * @param _proprietor Site Proprietor to load into.
	 * @param _rootDir Root directory of site.
	 */
	public FileSystemLoader(SiteProprietor _proprietor, File _rootDir) {
		this.siteProprietor = _proprietor;
		this.rootDirectory = _rootDir;
	}


	/**
	 * Recurses through directories to check if each file exists in the siteProprietor.
	 * If not, the file is added to the siteProprietor as a WebObjectProprietor Object.
	 */
	public void loadFiles(){
		if (rootDirectory.isDirectory()) {
			descender(rootDirectory);
		} else Logger.getLogger("awesome.server").warning("Root not a directory: " + rootDirectory.getAbsolutePath());
	}

	private void descender(File currDir) {
		for (File currFile:currDir.listFiles()) {
			if (currFile.isDirectory()){
				descender(currFile); //recurse into directory
			} else if (!siteProprietor.containsKey(currFile.toString())){
				loadIndividualFile(currFile);
			}
		}
	}

	private void loadIndividualFile(File toLoad){
		Logger.getLogger("awesome.server").info("Loading file: " + toLoad.toString());
		WebObjectProprietor currProp = new WebObjectProprietor(toLoad); //load file into memory
		siteProprietor.put(toLoad.toString(), currProp); //add it to proprietor
	}
}
